<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\TenantProduct\Logic;

use Hyperf\Di\Annotation\Inject;
use MoChat\Plugin\TenantProduct\Contract\TenantProductSkuContract;

/**
 * 套餐管理- 列表.
 *
 * Class IndexLogic
 */
class IndexLogic
{
    /**
     * @Inject
     * @var TenantProductSkuContract
     */
    protected $tenantProductSkuService;

    /**
     * @param array $params 请求参数
     * @param array $adminUser 请求参数
     * @return array 响应数组
     */
    public function handle(array $params, array $adminUser): array
    {
        # # 查询数据
        $list = $this->tenantProductSkuService->getTenantProductSkuBySpuId(1, $params['startTime'], $params['endTime'], $params['status'], ['id', 'spu_id', 'attributes', 'price', 'market_price', 'status', 'audit_status', 'updated_at']);
        foreach ($list as &$item) {
            $attributes = $this->tenantProductSkuService->getTenantProductSkuValuesById(explode(',', $item['attributes']));
            foreach ($attributes as $v) {
                if ($v['attributeName'] === '套餐名称') {
                    $item['name'] = $v['attributeValue'];
                }
                if ($v['attributeName'] === '服务周期') {
                    $item['cycle'] = $v['attributeValue'];
                }
                if ($v['attributeName'] === '套餐功能') {
                    $item['roleMenu'] = $v['attributeValue'];
                }
                if ($v['attributeName'] === '使用范围') {// 1：仅官方，2：仅代理，3：不限制
                    $item['useScope'] = $v['attributeValue'];
                    if ($params['type'] === 2 && $v['attributeValue'] !== 3) {
                        if ($adminUser['isRoot'] === 1 && $v['attributeValue'] === 2) {
                            unset($item);
                            continue;
                        }
                        if ($adminUser['isRoot'] === 0 && $v['attributeValue'] === 1) {
                            unset($item);
                            continue;
                        }
                    }
                }
                if ($v['attributeName'] === '默认员工') {// 不限制|整数（23）
                    $item['maxEmployee'] = $v['attributeValue'];
                }
                if ($v['attributeName'] === '默认账号') {// 不限制|整数（23）
                    $item['maxCorp'] = $v['attributeValue'];
                }
                unset($item['attributes']);
            }
        }
        if (! empty($params['name'])) {
            foreach ($list as $key => $val) {
                if (! str_contains($val['name'], $params['name'])) {
                    unset($list[$key]);
                }
            }
        }
        return array_merge($list);
    }
}
